package core

import (
	"fmt"
	"io"
	"net/http"
)

type HttpAmiServer struct {
	Me      string `json:"me"`      // 自己的身份
	Port    int    `json:"port"`    // 开放端口
	Channel string `json:"channel"` // 频道全大写
}

// 设置服务器信息
func (serv *HttpAmiServer) LoadConfig(jc *JsonConfig) {
	serv.Me = jc.Me
	serv.Port = jc.Port
	serv.Channel = jc.Channel
	AmiLoger.Printf("LoadConfig : %v", serv)
}

// 处理请求
func (serv HttpAmiServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	AmiLoger.Println("Listener Once -- ")
	// 接收Channel数据
	data, err := io.ReadAll(r.Body)
	if err != nil {
		AmiLoger.Printf("err: %v\n", err)
		return
	}
	me := serv.Me
	channel := string(data)
	AmiLoger.Printf("req.channel = %v\n", channel)
	if serv.Channel == channel {
		w.Write([]byte(me))
	} else {
		// w.Write([]byte("Don't-Know"))
		AmiLoger.Println("Cut Down")
	}
}

// 运行服务器
func (serv HttpAmiServer) RunServer() {
	addr := fmt.Sprintf("0.0.0.0:%v", serv.Port)
	http.Handle("/httpami", serv)
	http.ListenAndServe(addr, nil)
}
